package com.example.wasaimovie.Service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.wasaimovie.Mapper.UserMapper;
import com.example.wasaimovie.Model.entity.User;
import com.example.wasaimovie.Model.support.ResponseResult;
import com.example.wasaimovie.Service.UserService;
import com.example.wasaimovie.Util.JwtTokenUtil;
import com.example.wasaimovie.Util.MD5Util;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    UserService userService;

    /**
     * 登录功能
     * @param user 用户信息
     * @return 登录结果
     */
    @Override
    public ResponseResult<Map<String, Object>> login(User user){
        ResponseResult<Map<String, Object>> result = null;
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("username", user.getUsername());
        List<User> userSelectResult = userService.list(qw);
        if (userSelectResult.isEmpty()){
            // 用户不存在
            result = new ResponseResult<>(400, "用户名不存在");
        } else {
            User userInfo = userSelectResult.get(0);
            if (!userInfo.getPassword()
                    .equals(MD5Util.md5To32String(user.getPassword(), userInfo.getUserSalt(), userInfo.getSaltIndex()))){
                System.out.println(MD5Util.md5To32String(user.getPassword(), user.getUserSalt(), user.getSaltIndex()));
                // 用户密码不正确
                // 用户不存在
                result = new ResponseResult<>(400, "用户名或密码错误");
            } else {
                // 登陆成功
                Map<String, Object> data = new HashMap<>();
                // 设置身份
                List<String> roles = new ArrayList<>();
                roles.add("user");
                String token = JwtTokenUtil.createToken(userInfo.getUsername(), roles, JwtTokenUtil.EXPIRATION_TIME);
                data.put("user", userInfo);
                data.put("token", token);
                result = new ResponseResult<>(data);
            }
        }
        return result;
    }

    /**
     * 注册功能
     * @param user 用户信息
     * @return 注册结果
     */
    @Override
    public ResponseResult<Map<String, Object>> register(User user){
        ResponseResult<Map<String, Object>> result = null;
        boolean exist = isExist(user);
        if (exist){
            // 用户已存在
            result = new ResponseResult<>(202, "用户信息已经存在");
        } else {
            // 用户不存在
            // 默认头像
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            user.setAvatar("6dcbec9e-5166-4e87-964e-bc9c5853a3d9");
            user.setNickname(UUID.randomUUID().toString().substring(0, 10) + "_" + (int)(Math.random() * 10000));
            user.setCreateTime(format.format(new Date()));
            // 密码加密
            String salt = RandomStringUtils.randomAlphabetic(10);
            int index = (int)(Math.random() * 10);
            String pwd = MD5Util.md5To32String(user.getPassword(), salt, index);
            user.setPassword(pwd);
            user.setUserSalt(salt);
            user.setSaltIndex(index);
            userService.save(user);
            result = new ResponseResult<>();
        }
        return result;
    }

    /**
     * 更新用户信息
     * @param user 用户信息
     */
    @Override
    public boolean userUpdate(User user) {
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("id", user.getId());
        // 密码MD5加密
        String salt = RandomStringUtils.randomAlphabetic(10);
        int index = (int)(Math.random() * 10);
        String pwd = MD5Util.md5To32String(user.getPassword(), salt, index);
        user.setUserSalt(salt);
        user.setSaltIndex(index);
        user.setPassword(pwd);
        // 用户头像设置
        String avatar = user.getAvatar();
        int i = avatar.lastIndexOf("/");
        avatar = avatar.substring(i+1);
        user.setAvatar(avatar);
        // 更新前的用户信息
        User user1 = userService.list(qw).get(0);
        if (avatar != "6dcbec9e-5166-4e87-964e-bc9c5853a3d9"){
            // 不是默认头像,删除原头像
            File oldimg = new File("D:\\javaweb\\IdeaProjects\\WaSaiMovie\\src\\main\\resources\\static\\image" + user1.getAvatar());
            oldimg.delete();
        }
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("id", user.getId());
        return userService.update(user, userQueryWrapper);
    }

    /**
     * 判断用户是否存在
     * @param user 用户信息
     * @return 是否存在
     */
    public boolean isExist(User user){
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("username", user.getUsername());
        List<User> list = userService.list(qw);
        return !list.isEmpty();
    }
}
